package fm.dongman.animefm.view.fragment

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.FRankContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.activity.WebViewActivity
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ComicModel
import fm.dongman.presenterlib.presenter.FRankPresenter
import kotlinx.android.synthetic.main.fragment_find_rank.*
import kotlinx.android.synthetic.main.item_ranking_preview.view.*
import org.jetbrains.anko.onClick

/**
 * 发现->榜单页面
 * Created by shize on 2017/9/28.
 */
class FRankFragment : BaseFragment(), FRankContract.IFRankView {
    private lateinit var mPresenter: FRankContract.IFRankPresenter

    private val mWeekHotComics: ArrayList<IModel.IComicModel> = ArrayList() // 本周最火
    private lateinit var mWeekHotAdapter: FRankAdapter // 本周最火适配器

    private val mComicTopComics: ArrayList<IModel.IComicModel> = ArrayList() // 本周最火
    private lateinit var mComicTopAdapter: FRankAdapter // 新番top适配器

    private val mDomesticComics: ArrayList<IModel.IComicModel> = ArrayList() // 本周最火
    private lateinit var mDomesticComicAdapter: FRankAdapter // 国产排行适配器

    private val mHaremComics: ArrayList<IModel.IComicModel> = ArrayList() // 本周最火
    private lateinit var mHaremComicAdapter: FRankAdapter // 后宫排行适配器

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater?.inflate(R.layout.fragment_find_rank, container, false)
        FRankPresenter(this, Injection.provideFrankRepository(container!!.context))
        return fragment!!
    }

    override fun initData() {
        loadingContent()
    }

    override fun bindData() {
        bindFragment()
        bindAdapter()
        mPresenter.startLoad()
    }

    /**
     * 绑定适配器
     */
    private fun bindAdapter() {
        // 本周最火
        mWeekHotAdapter = FRankAdapter(activity, mWeekHotComics)
        mLvRankingPreviewHot.adapter = mWeekHotAdapter
        mLvRankingPreviewHot.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        // 新番top
        mComicTopAdapter = FRankAdapter(activity, mComicTopComics)
        mLvRankingNew.adapter = mComicTopAdapter
        mLvRankingNew.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        // 国产排行
        mDomesticComicAdapter = FRankAdapter(activity, mDomesticComics)
        mLvRankingDomestic.adapter = mDomesticComicAdapter
        mLvRankingDomestic.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        // 后宫排行
        mHaremComicAdapter = FRankAdapter(activity, mHaremComics)
        mLvRankingHarem.adapter = mHaremComicAdapter
        mLvRankingHarem.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    }

    /**
     * 绑定 Fragment 对应事件方法
     */
    private fun bindFragment() {
        mRlWeekDetails.onClick {
            startRankInfo(RankInfoFragment.FIND_INFO_WEEK_HOT) // 本周最火
        }
        mRlNewRankTop.onClick {
            startRankInfo(RankInfoFragment.FIND_INFO_NET_TOP) // 新番top
        }
        mRlDomesticComic.onClick {
            startRankInfo(RankInfoFragment.FIND_INFO_GUOCHAN) // 国产排行
        }
        mRlHaremComic.onClick {
            startRankInfo(RankInfoFragment.FIND_INFO_HAREM) // 后宫排行
        }
        mPresenter.getMoreRank()
    }

    /**
     * 启动漫榜详情页
     * @param type 类型
     */
    private fun startRankInfo(type: String) {
        val intent = Intent(activity, SingleActivity::class.java)
        intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_RANK_INFO)
        intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, type)
        ActivityHelper.startActivity(activity, intent)
    }

    override fun setPresenter(presenter: FRankContract.IFRankPresenter) {
        mPresenter = presenter
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    override fun showNoNetwork() {
        mFRankMultiStateLayout?.changeState(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
//        ToastHelper.getInstance(activity).showError("发现->榜单页面加载失败")
    }

    override fun showFRankHot(weekHotComicRank: List<IModel.IComicModel>) {
        loadedContent()
        mWeekHotComics.clear()
        mWeekHotComics.addAll(weekHotComicRank)
        mWeekHotAdapter.notifyDataSetChanged()
    }

    override fun showFRankTop(comicTopRank: List<IModel.IComicModel>) {
        mComicTopComics.clear()
        mComicTopComics.addAll(comicTopRank)
        mComicTopAdapter.notifyDataSetChanged()
    }

    override fun showFRankDomestic(domesticComicRank: List<IModel.IComicModel>) {
        mDomesticComics.clear()
        mDomesticComics.addAll(domesticComicRank)
        mDomesticComicAdapter.notifyDataSetChanged()
    }

    override fun showFRankHarem(haremComicRank: List<IModel.IComicModel>) {
        mHaremComics.clear()
        mHaremComics.addAll(haremComicRank)
        mHaremComicAdapter.notifyDataSetChanged()
    }

    override fun showFRankMore(url: String) {
        mFRankMoreRank.onClick {
            activity.startActivity(WebViewActivity.getIntent(activity, url, true))
        }
    }

    /**
     * 加载中
     */
    private fun loadingContent() = mFRankMultiStateLayout?.changeState(MultiStateLayout.LOADING)

    /**
     * 加载完成
     */
    private fun loadedContent() {
        mFRankMultiStateLayout?.changeState(MultiStateLayout.SUCCESS)
    }

    companion object {
        private var FRAGMENT_INSTANCE: FRankFragment? = null

        /**
         * 获取实例
         */
        fun getInstance(): FRankFragment {
            if (FRAGMENT_INSTANCE == null) {
                FRAGMENT_INSTANCE = FRankFragment()
            }
            return FRAGMENT_INSTANCE!!
        }

        /**
         * 销毁实例
         */
        fun destroyInstance() {
            FRAGMENT_INSTANCE = null
        }
    }

    /**
     * 缩略列表适配器
     */
    private class FRankAdapter(private val mContext: Context, private val mData: List<IModel.IComicModel>)
        : RecyclerView.Adapter<FRankViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): FRankViewHolder =
                FRankViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_ranking_preview, null))

        override fun onBindViewHolder(holder: FRankViewHolder?, position: Int) {
            val comic: ComicModel = mData[position] as ComicModel
            holder!!.mTvNum.text = (position + 1).toString()
            holder.mComicTitle.text = comic.title
        }

        override fun getItemCount(): Int = mData.size
    }

    /**
     * 缩略列表适配器 ViewHolder
     */
    class FRankViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mTvNum: TextView = itemView.mTvRankingPreviewNum
        val mComicTitle: TextView = itemView.mTvRankingPreviewTitle
    }
}